<!-- 表格组件 -->
<script lang="tsx" setup>
import { toRaw } from "vue";

import type { TableColumnOption } from "@/components/table-widget/table-widget.vue";
import TableWidget from "@/components/table-widget/table-widget.vue";
// import ContentManage from "./content-manage.vue";
import {
	jeecgBootPlanDeleteUsingPost,
	jeecgBootPlanPublishUsingPost,
	jeecgBootPlanUnshelveUsingPost,
  jeecgBootPlanCoursesUsingGet
} from "@/genapi/exam";

import { injectState } from "../state";
import {useUserStore} from "@/stores/user"

// import testData from './assets/testData.json'

defineOptions({ name: "Sheet" });

const {
	selectedList,
	tableRef,
	detailDialogRef,
	page: { records, isLoading, execute },
} = injectState()!;

watch(records, () => tableRef.value?.table?.clearSelection());
// 测试数据
// records.value = testData

//获取内容管理数据
let contentmanagedata = ref([])
const  getContentManageData = async(row) => {
  console.log(row.id)
     let res = await jeecgBootPlanCoursesUsingGet({
			params:{
          planId : row.id
        }
		})
    console.log(res.result)
    // console.log(res.result[0].coverFile)
    contentmanagedata.value = res.result
    // .then(res => contentmanagedata.value = res.result)
    // console.log(contentmanagedata)
  detailDialogRef.value?.trigger("content", contentmanagedata.value)
  contentmanagedata.value = []
}

const onAudit = async (row: (typeof records.value)[0]) => {
  if(row.statusText === '已发布'){
    ElMessage.warning("已发布内容不能删除");
    return
  }
	await ElMessageBox.confirm(`确认删除吗？`, {
		type: "info",
		title: "提示",
	});
	await jeecgBootPlanDeleteUsingPost({
		params: {
			id: row.id!,
		},
	});
	ElMessage.success("处理成功");
	await execute();
};

const handleDataStatus = async (row) => {
	if (row.status === "0") {
		await jeecgBootPlanPublishUsingPost({
			params: {
				planId: row.id,
			},
		});
		ElMessage.success("处理成功");
		await execute();
	} else if (row.status === "1") {
		// await jeecgBootPlanUnshelveUsingPost({
		// 	params: {
		// 		planId: row.id,
		// 	},
		// });
    const { authorization } = useUserStore();
    const config = {
            headers: {
                    "X-Access-Token": authorization,
                    "content-type":"application/x-www-form-urlencoded"
            },
    };
    const params = new URLSearchParams();
    params.append("planId", row.id);
    await axios.post(`/jeecg-boot/plan/unshelve`, params, config);
		ElMessage.success("处理成功");
		await execute();
	}
};

const columns: TableColumnOption<(typeof records.value)[0]>[] = [
	{
		label: "课程名称",
		width: "200",
		formatter: (row) => row.name ?? "-",
	},
	{
		label: "培训类型",
		width: "150",
		// formatter: (row) => row.type ?? "-",
		formatter: (row) => {
			return (
				<el-text type="primary" style="color:#409eff">
					{row.typeText ?? "-"}
				</el-text>
			);
		},
	},
	{
		label: "标签",
		width: "270",
		// formatter: (row) => row.tag ?? "-",
		formatter: (row) => {
			// debugger;
			// let data = JSON.parse(row.tag);
			// if (typeof data !== "array") {
			// 	data = [data];
			// }
			return row.tag.map((item) => {
				return (
					<el-tag size="mini" type="success">
						{item.substring(1, item.length - 1)}
					</el-tag>
				);
			});
		},
	},
	{
		label: "学分",
		width: "120",
		formatter: (row) => row.credits ?? "-",
	},
	{
		label: "课节数",
		width: "120",
		formatter: (row) => row.courseNum ?? "-",
	},
	{
		label: "创建人",
		width: "150",
		formatter: (row) => row.createBy ?? "-",
	},
	{
		label: "排序",
		width: "150",
		// formatter: (row) => row.sortOrder ?? "-",
		formatter: (row) => {
			return (
				<el-text
					style="
            width: 60px;
            background-color: #f7f8fa;
            display: inline-block;
            text-align: center;
                    "
				>
					{row.sort ?? "-"}
				</el-text>
			);
		},
	},
	{
		label: "发布状态",
		width: "100",
		formatter: (row) => {
			if (row.status === "0") {
				return (
					<div
						style={{
							color: "#FE4848",
							height: "26px",
							width: "60px",
							backgroundColor: "#FFF2F2",
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							marginLeft: "4px",
						}}
					>
						<span>{row.statusText}</span>
					</div>
				);
			} else if (row.status === "1") {
				return (
					<div
						style={{
							color: "#00B42A",
							height: "26px",
							width: "60px",
							backgroundColor: "#E8FFEA",
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							marginLeft: "4px",
						}}
					>
						<span>{row.statusText}</span>
					</div>
				);
			} else if (row.status === "2") {
				return (
					<div
						style={{
							color: "#FE4848",
							height: "26px",
							width: "60px",
							backgroundColor: "#FFF2F2",
							display: "flex",
							justifyContent: "center",
							alignItems: "center",
							marginLeft: "4px",
						}}
					>
						<span>{row.statusText}</span>
					</div>
				);
			} else {
				return "--";
			}
		},
	},
	{
		label: "操作",
		export: false,
		fixed: "right",
		noExport: true,
		formatter(row) {
			return (
				<>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => handleDataStatus(row)}
					>
						{row.status === "0" ? "发布" : "下架"}
					</el-button>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => getContentManageData(row)}
					>
						内容管理
					</el-button>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => detailDialogRef.value?.trigger("write", row)}
					>
						编辑
					</el-button>
					<el-button
						size="small"
						type="primary"
						text
						onClick={() => onAudit(row)}
					>
						删除
					</el-button>
				</>
			);
		},
	},
];
</script>

<template>
	<TableWidget
		fit
		ref="tableRef"
		v-loading="isLoading"
		:data="records"
		:columns="columns"
		h="100%!"
		@selection-change="(rows: any) => (selectedList = toRaw(rows))"
	/>
  <content-manage></content-manage>
</template>
<style scoped lang="scss">
.el-table td.el-table__cell div {
	display: flex;
	justify-content: center !important;
}
</style>
